<!--  -->
<template>
  <div class='AddAndEdit'>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="25%"
      :before-close="handleClose"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        class="demo-ruleForm"
        label-width='100px'
      >
        <el-form-item
          label="工单类型"
          prop="type"
        >
          <el-select
            v-model="ruleForm.type"
            placeholder="请选择"
            style="width:100%;"
          >
            <el-option
              v-for="item in csworkTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="申请人部门"
          prop="applyDepartRecive"
        >
          <el-cascader
            style="width:100%;"
            ref="cascaderAddr"
            v-model="ruleForm.applyDepartRecive"
            :options="applyDepartOptions"
            @change="handleChange"
            :props='props'
          ></el-cascader>
        </el-form-item>
        <el-form-item
          label="角色"
          prop="role"
        >
          <el-select
            filterable
            ref="role"
            style="width:100%;"
            @change="handleChanges"
            v-model="ruleForm.role"
            placeholder="请选择"
          >
            <el-option
              v-for="item in roleOptions"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="人员"
          prop="user"
        >
          <el-select
            ref="user"
            style="width:100%;"
            v-model="ruleForm.user"
            placeholder="请选择"
            @change="handleChangeuser"
          >
            <el-option
              v-for="item in userOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          @click="dialogVisible = false"
          icon="el-icon-circle-close"
        >取 消</el-button>
        <el-button
          type="primary"
          icon="el-icon-circle-check"
          @click="doSubmit"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import { getDicType } from '@/api/common'
import { Tree, RoleList, getUserByDepRole, addObj } from '@/api/admin/csworkorderconfig/csworkorderconfig'
export default {
  // import引入的组件需要注入到对象中才能使用
  components: {},
  data () {
    // 这里存放数据
    return {
      title: '添加工单配置',
      ruleForm: {
        id: '',
        user: "",
        role: '',
        type: '',
        thsAreaCode: '',
        applyDepartRecive: [],
        applyDepartLabel: '',
        userName: '',
        roleName: ''
      },
      csworkTypeOptions: [],
      roleOptions: [],//角色
      applyDepartOptions: [],//申请人
      userOptions: [],
      dialogVisible: false,

      rules: {
        user: [{ required: true, message: '请选择人员', trigger: 'change' }],
        role: [{ required: true, message: '请选择角色', trigger: 'change' }],
        applyDepartRecive: [{ required: true, message: '请选择申请人部门', trigger: 'change' }],
        type: [{ required: true, message: '请选择工单类型', trigger: 'change' }]
      },
      navs: [],
      props: {
        label: 'name',
        value: 'deptId'
      },
      method: '',
      message: ''
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    // 确定
    doSubmit () {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          addObj(this.ruleForm).then(res => {
            this.$message.success(this.message)
            this.dialogVisible = false
            this.$emit("refreshList")
          })
        } else {
          return false;
        }
      });
    },
    handleChange () {
      this.navs = []
      let arrays = this.$refs["cascaderAddr"].getCheckedNodes()[0]
      let i = 1
      while (i) {
        this.navs.splice(0, 0, arrays.label)
        if (arrays.parent) {
          arrays = arrays.parent
        } else {
          i = 0
        }
      }
      this.ruleForm.applyDepartLabel = this.navs.join('/')
      this.ruleForm.user = ''
      this.ruleForm.userName = ''
      this.getuserOptions()
    },
    handleChanges (value) {
      this.roleOptions.forEach(item => {
        if (item.roleId === value) {
          this.ruleForm.roleName = item.roleName
        }
      })
      this.ruleForm.user = ''
      this.ruleForm.userName = ''
      this.getuserOptions()
    },
    handleChangeuser (value) {
      this.userOptions.forEach(item => {
        if (item.id === value) {
          this.ruleForm.userName = item.name
        }
      })
    },
    getuserOptions () {
      if (!this.ruleForm.applyDepartRecive.length || !this.ruleForm.role) {
        return
      }
      getUserByDepRole({
        depId: this.ruleForm.applyDepartRecive[this.ruleForm.applyDepartRecive.length - 1],
        roleId: this.ruleForm.role
      }).then(res => {
        this.userOptions = res.data.data
      })
    },
    handleClose () {
      this.dialogVisible = false
    },
    init (method, id) {
      this.method = method
      if (this.$refs['ruleForm']) {
        this.$refs['ruleForm'].resetFields()
      }
      Tree().then(res => {
        this.applyDepartOptions = res.data.data
        this.handleTree(this.applyDepartOptions)
      })
      RoleList().then(res => {
        this.roleOptions = res.data.data
      })
      getDicType('cswork_type').then(res => {
        this.csworkTypeOptions = res.data.data
      })
      this.ruleForm.id = id
      if (method == 'view') {
        this.title = '查看工单配置'
      } else if (method == 'add') {
        this.title = '添加工单配置'
        this.message = "添加成功"
      } else if (method == "edit") {
        this.title = '修改工单配置'
        this.message = "修改成功"
        setTimeout(() => {
          this.ruleForm = JSON.parse(JSON.stringify(id))
          this.ruleForm.applyDepartRecive = this.ruleForm.applyDepartView.split(',')
          for (var i = 0; i < this.ruleForm.applyDepartRecive.length; i++) {
            this.ruleForm.applyDepartRecive[i] = parseInt(this.ruleForm.applyDepartRecive[i])
          }
          this.ruleForm.role = parseInt(this.ruleForm.role)
          this.ruleForm.type = this.ruleForm.type + ''
          this.getuserOptions()
        }, 1)
      }
      this.dialogVisible = true
    },
    handleTree(treeData) {
      treeData.forEach(item => {
        if (item.children.length > 0) {
          this.handleTree(item.children)
        } else {
          item.children = undefined
        }
      })
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {

  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {

  },
  beforeCreate () { }, // 生命周期 - 创建之前
  beforeMount () { }, // 生命周期 - 挂载之前
  beforeUpdate () { }, // 生命周期 - 更新之前
  updated () { }, // 生命周期 - 更新之后
  beforeDestroy () { }, // 生命周期 - 销毁之前
  destroyed () { }, // 生命周期 - 销毁完成
  activated () { } // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类
</style>
